using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using CPlatePrintSys.Domain.DTOs;
using CPlatePrintSys.Domain.Models;
using CPlatePrintSys.Domain.Services;
using CPlatePrintSys.DataAccess.Repositories;
using Newtonsoft.Json;
using CPlatePrintSys.Infrastructure.Repositories;

namespace CPlatePrintSys.Application.Services
{
    /// <summary>
    /// 工作空间服务实现（仅本地存储）
    /// </summary>
    [Obsolete]
    public class WorkSpaceService : IWorkSpaceService
    {
        private readonly KmacsService _kmacsService;
        private readonly AmService _amService;
        private readonly CadWinService _cadWinService;
        private readonly ShipInfoService _shipInfoService;
        private readonly IPlateAnnotationInfoRepository _plateAnnotationRepository;
        private WorkSpace _currentWorkSpace;
        private List<WorkSpace> _workSpaces = new List<WorkSpace>();

        public WorkSpaceService(
            KmacsService kmacsService,
            AmService amService,
            CadWinService cadWinService,
            ShipInfoService shipInfoService,
            IPlateAnnotationInfoRepository plateAnnotationRepository)
        {
            _kmacsService = kmacsService;
            _amService = amService;
            _cadWinService = cadWinService;
            _shipInfoService = shipInfoService;
            _plateAnnotationRepository = plateAnnotationRepository;
            
            // 初始化时加载本地工作空间数据
            LoadWorkSpacesFromLocalStorage();
        }

        public async Task<List<WorkSpace>> GetAllWorkSpacesAsync()
        {
            return await Task.FromResult(_workSpaces);
        }

        public async Task<WorkSpace> GetWorkSpaceByIdAsync(int id)
        {
            return await Task.FromResult(_workSpaces.FirstOrDefault(w => w.Id == id));
        }

        public async Task<WorkSpace> CreateWorkSpaceAsync(WorkSpace workSpace)
        {
            workSpace.Id = _workSpaces.Count > 0 ? _workSpaces.Max(w => w.Id) + 1 : 1;
            workSpace.CreatedAt = DateTime.Now;
            workSpace.LastModifiedAt = DateTime.Now;
            workSpace.IsActive = true;
            
            _workSpaces.Add(workSpace);
            SaveWorkSpacesToLocalStorage();
            
            return workSpace;
        }

        public async Task<bool> UpdateWorkSpaceAsync(WorkSpace workSpace)
        {
            var existingWorkSpace = _workSpaces.FirstOrDefault(w => w.Id == workSpace.Id);
            if (existingWorkSpace == null) return false;

            existingWorkSpace.Name = workSpace.Name;
            existingWorkSpace.Description = workSpace.Description;
            existingWorkSpace.WorkSpaceNodes = workSpace.WorkSpaceNodes;
            existingWorkSpace.LastModifiedAt = DateTime.Now;
            
            SaveWorkSpacesToLocalStorage();
            return true;
        }

        public async Task<bool> DeleteWorkSpaceAsync(int id)
        {
            var workSpace = _workSpaces.FirstOrDefault(w => w.Id == id);
            if (workSpace == null) return false;

            // 如果删除的工作空间是当前工作空间，需要清除当前工作空间引用
            if (_currentWorkSpace != null && _currentWorkSpace.Id == id)
            {
                _currentWorkSpace = null;
            }

            _workSpaces.Remove(workSpace);
            SaveWorkSpacesToLocalStorage();
            return true;
        }

        public async Task<List<WorkSpaceRecord>> GetRecentWorkSpaceRecordsAsync(int count = 5)
        {
            var records = _workSpaces
                .Where(w => w.IsActive)
                .OrderByDescending(w => w.LastModifiedAt)
                .Take(count)
                .Select(w => new WorkSpaceRecord
                {
                    Id = w.Id,
                    Name = w.Name,
                    Description = w.Description,
                    LastModifiedAt = w.LastModifiedAt,
                    CreatedBy = w.CreatedBy,
                    NodeCount = w.WorkSpaceNodes?.Count ?? 0,
                    PreviewInfo = GeneratePreviewInfo(w.WorkSpaceNodes)
                })
                .ToList();

            return await Task.FromResult(records);
        }

        public async Task<List<WorkSpaceNode>> GetFullWorkDirectoryTreeAsync()
        {
            try
            {
                // 从数据库获取PlateAnnotationInfo数据来构建工作目录树
                var plateAnnotationInfos = await GetPlateAnnotationInfosFromDatabaseAsync();
                
                // 如果数据库中没有数据，返回空列表
                if (plateAnnotationInfos == null || !plateAnnotationInfos.Any())
                {
                    System.Diagnostics.Debug.WriteLine("数据库中没有PlateAnnotationInfo数据，返回空的工作目录树");
                    return new List<WorkSpaceNode>();
                }
                
                System.Diagnostics.Debug.WriteLine($"从数据库获取到 {plateAnnotationInfos.Count} 条PlateAnnotationInfo记录，开始构建工作目录树");
                
                // 构建工作目录树
                var workDirectoryTree = new List<WorkSpaceNode>();
                
                // 按船号分组
                var shipGroups = plateAnnotationInfos.GroupBy(p => p.StreamShipNo).ToList();
                
                foreach (var shipGroup in shipGroups)
                {
                    var shipNode = new WorkSpaceNode
                    {
                        Name = shipGroup.Key,
                        NodeType = "Ship",
                        NodeValue = shipGroup.Key,
                        SortOrder = 1
                    };
                    
                    // 按LOT号分组
                    var lotGroups = shipGroup.GroupBy(p => p.LotNo).ToList();
                    
                    foreach (var lotGroup in lotGroups)
                    {
                        var lotNode = new WorkSpaceNode
                        {
                            Name = lotGroup.Key,
                            NodeType = "Lot",
                            NodeValue = lotGroup.Key,
                            Parent = shipNode,
                            SortOrder = 2
                        };
                        
                        // 添加加工序列
                        foreach (var plateInfo in lotGroup)
                        {
                            var sequenceNode = new WorkSpaceNode
                            {
                                Name = plateInfo.Sequence,
                                NodeType = "Sequence",
                                NodeValue = plateInfo.Sequence,
                                Parent = lotNode,
                                SortOrder = 3
                            };
                            
                            lotNode.Children.Add(sequenceNode);
                        }
                        
                        shipNode.Children.Add(lotNode);
                    }
                    
                    workDirectoryTree.Add(shipNode);
                }
                
                System.Diagnostics.Debug.WriteLine($"构建完成，工作目录树包含 {workDirectoryTree.Count} 个船号节点");
                return workDirectoryTree;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"构建工作目录树失败: {ex.Message}");
                // 如果数据库查询失败，返回空列表而不是模拟数据
                return new List<WorkSpaceNode>();
            }
        }

        public async Task<List<PlateAnnotationInfo>> GetPlateAnnotationInfosByWorkSpaceNodeAsync(WorkSpaceNode node)
        {
            if (node == null) return new List<PlateAnnotationInfo>();

            try
            {
                // 根据节点类型筛选数据
                var allPlateInfos = new List<PlateAnnotationInfo>();
                
                // 获取KMACS数据
                var kmacsList = await _kmacsService.GetProcessInfosAsync();
                var amList = await _amService.GetDrawingInfosAsync();
                var cadwinList = await _cadWinService.GetDrawingInfosAsync();
                var streamShipMap = await _shipInfoService.GetStreamShipToMotherShipMapAsync();

                // 合并数据（参考ProcessSequenceViewModel.SyncAndMergeAllSourcesAsync）
                var result = new List<PlateAnnotationInfo>();
                foreach (var kmacs in kmacsList)
                {
                    var keyShip = kmacs.StreamShipNo;
                    var keyLot = kmacs.LotNo;
                    var keySeq = kmacs.Sequence;

                    // 根据节点类型进行筛选
                    bool shouldInclude = false;
                    switch (node.NodeType)
                    {
                        case "Ship":
                            shouldInclude = keyShip == node.NodeValue;
                            break;
                        case "Lot":
                            shouldInclude = keyLot == node.NodeValue;
                            break;
                        case "Sequence":
                            shouldInclude = keySeq == node.NodeValue;
                            break;
                    }

                    if (shouldInclude)
                    {
                        var am = amList.FirstOrDefault(a => a.ShipNo == keyShip && a.LotNo == keyLot && a.Sequence == keySeq);
                        if (am != null)
                        {
                            var info = PlateAnnotationInfoFactory.FromAmDto(am);
                            // 保留AM数据的图纸要求信息，补充KMACS的钢板信息
                            info.SheetConsistentNo = kmacs.SheetConsistentNo;
                            info.CNO = kmacs.CNO;
                            info.MergedInfo = kmacs.MergedInfo;
                            info.SheetSpecCls = kmacs.SheetSpecCls;
                            info.SheetSpecThickness = kmacs.SheetSpecThickness;
                            info.SheetSpecLength = kmacs.SheetSpecLength;
                            info.SheetSpecWidth = kmacs.SheetSpecWidth;
                            info.PlanUsedDate = kmacs.PlanUsedDate;
                            result.Add(info);
                            continue;
                        }
                        
                        var cad = cadwinList.FirstOrDefault(c => c.ShipNo == keyShip && c.LotNo == keyLot && c.Sequence == keySeq);
                        if (cad != null)
                        {
                            var info = PlateAnnotationInfoFactory.FromCadWinDto(cad);
                            // 保留CadWin数据的图纸要求信息，补充KMACS的钢板信息
                            info.SheetConsistentNo = kmacs.SheetConsistentNo;
                            info.CNO = kmacs.CNO;
                            info.MergedInfo = kmacs.MergedInfo;
                            info.SheetSpecCls = kmacs.SheetSpecCls;
                            info.SheetSpecThickness = kmacs.SheetSpecThickness;
                            info.SheetSpecLength = kmacs.SheetSpecLength;
                            info.SheetSpecWidth = kmacs.SheetSpecWidth;
                            info.PlanUsedDate = kmacs.PlanUsedDate;
                            result.Add(info);
                            continue;
                        }
                        
                        // 如果AM和CadWin都没有匹配数据，使用KMACS数据，但需要设置默认的图纸要求信息
                        var kmacsInfo = PlateAnnotationInfoFactory.FromKmacsDto(kmacs);
                        // 设置默认的图纸要求信息（与钢板规格相同，因为KMACS数据中只有钢板信息）
                        kmacsInfo.DesignSpecCls = kmacs.SheetSpecCls;
                        kmacsInfo.DesignSpecThickness = kmacs.SheetSpecThickness;
                        kmacsInfo.DesignSpecLength = kmacs.SheetSpecLength;
                        kmacsInfo.DesignSpecWidth = kmacs.SheetSpecWidth;
                        result.Add(kmacsInfo);
                    }
                }

                return result;
            }
            catch (Exception ex)
            {
                // 如果系统不可用，返回空列表
                return new List<PlateAnnotationInfo>();
            }
        }

        public async Task SaveWorkSpaceToLocalConfigAsync(WorkSpace workSpace)
        {
            try
            {
                // 将工作空间信息保存到App.config
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

                // 更新或添加工作空间基本信息
                UpdateOrAddAppSetting(config, "CurrentWorkSpaceId", workSpace.Id.ToString());
                UpdateOrAddAppSetting(config, "CurrentWorkSpaceName", workSpace.Name);
                UpdateOrAddAppSetting(config, "CurrentWorkSpaceLastModified", workSpace.LastModifiedAt.ToString("yyyy-MM-dd HH:mm:ss"));

                //TODO: rewirte save 
                // 保存工作空间节点信息（JSON格式）
                var nodesJson = JsonConvert.SerializeObject(workSpace.WorkSpaceNodes);
                //var nodesJson = JsonSerializer.SerializeObject(workSpace.WorkSpaceNodes, );
                UpdateOrAddAppSetting(config, "CurrentWorkSpaceNodes", nodesJson);

                config.Save(ConfigurationSaveMode.Modified);

                ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception ex)
            {
                // 如果App.config保存失败，尝试保存到文件
                SaveWorkSpaceToFile(workSpace);
            }
        }

        private void UpdateOrAddAppSetting(Configuration config, string key, string value)
        {
            if (config.AppSettings.Settings[key] != null)
            {
                config.AppSettings.Settings[key].Value = value;
            }
            else
            {
                config.AppSettings.Settings.Add(key, value);
            }
        }

        public async Task<WorkSpace> LoadWorkSpaceFromLocalConfigAsync()
        {
            try
            {
                var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                
                var workSpaceIdStr = config.AppSettings.Settings["CurrentWorkSpaceId"]?.Value;
                if (string.IsNullOrEmpty(workSpaceIdStr) || !int.TryParse(workSpaceIdStr, out int workSpaceId))
                {
                    return null;
                }

                var workSpace = new WorkSpace
                {
                    Id = workSpaceId,
                    Name = config.AppSettings.Settings["CurrentWorkSpaceName"]?.Value ?? "",
                    LastModifiedAt = DateTime.Parse(config.AppSettings.Settings["CurrentWorkSpaceLastModified"]?.Value ?? DateTime.Now.ToString())
                };

            // 加载工作空间节点信息
            var nodesJson = config.AppSettings.Settings["CurrentWorkSpaceNodes"]?.Value;
                if (!string.IsNullOrEmpty(nodesJson))
                {
                    workSpace.WorkSpaceNodes = JsonConvert.DeserializeObject<List<WorkSpaceNode>>(nodesJson);
                }

                return workSpace;
            }
            catch (Exception ex)
            {
                // 如果App.config加载失败，尝试从文件加载
                return LoadWorkSpaceFromFile();
            }
        }

        public WorkSpace GetCurrentWorkSpace()
        {
            return _currentWorkSpace;
        }

        public void SetCurrentWorkSpace(WorkSpace workSpace)
        {
            _currentWorkSpace = workSpace;
        }

        #region 私有方法

        private void LoadWorkSpacesFromLocalStorage()
        {
            try
            {
                var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "workspaces.json");
                if (File.Exists(configPath))
                {
                    var json = File.ReadAllText(configPath);
                    _workSpaces = JsonConvert.DeserializeObject<List<WorkSpace>>(json) ?? new List<WorkSpace>();
                }
            }
            catch (Exception ex)
            {
                // 如果加载失败，使用空列表
                _workSpaces = new List<WorkSpace>();
            }
        }

        private void SaveWorkSpacesToLocalStorage()
        {
            try
            {
                var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "workspaces.json");
                var json = JsonConvert.SerializeObject(_workSpaces, Formatting.Indented);
                File.WriteAllText(configPath, json);
            }
            catch (Exception ex)
            {
                // 保存失败时的处理
            }
        }

        private List<WorkSpaceNode> GetMockWorkDirectoryTree()
        {
            var workDirectoryTree = new List<WorkSpaceNode>();

            // 原有的测试数据
            var root1 = new WorkSpaceNode("N11519") { NodeType = "Ship", NodeValue = "N11519" };
            var a101a = new WorkSpaceNode("A101A", root1) { NodeType = "Lot", NodeValue = "A101A" };
            root1.Children.Add(a101a);
            a101a.Children.Add(new WorkSpaceNode("7PA001", a101a) { NodeType = "Sequence", NodeValue = "7PA001" });
            a101a.Children.Add(new WorkSpaceNode("7PA002", a101a) { NodeType = "Sequence", NodeValue = "7PA002" });
            a101a.Children.Add(new WorkSpaceNode("7PA003", a101a) { NodeType = "Sequence", NodeValue = "7PA003" });
            a101a.Children.Add(new WorkSpaceNode("7PA004", a101a) { NodeType = "Sequence", NodeValue = "7PA004" });
            
            var root2 = new WorkSpaceNode("N11520") { NodeType = "Ship", NodeValue = "N11520" };
            var root3 = new WorkSpaceNode("N11521") { NodeType = "Ship", NodeValue = "N11521" };
            
            workDirectoryTree.Add(root1);
            workDirectoryTree.Add(root2);
            workDirectoryTree.Add(root3);

            // 新增一对多测试数据
            // S005 船号对应多个LOT号
            var s005 = new WorkSpaceNode("S005") { NodeType = "Ship", NodeValue = "S005" };
            var l005a = new WorkSpaceNode("L005A", s005) { NodeType = "Lot", NodeValue = "L005A" };
            var l005b = new WorkSpaceNode("L005B", s005) { NodeType = "Lot", NodeValue = "L005B" };
            var l005c = new WorkSpaceNode("L005C", s005) { NodeType = "Lot", NodeValue = "L005C" };
            
            l005a.Children.Add(new WorkSpaceNode("SEQ008", l005a) { NodeType = "Sequence", NodeValue = "SEQ008" });
            l005b.Children.Add(new WorkSpaceNode("SEQ009", l005b) { NodeType = "Sequence", NodeValue = "SEQ009" });
            l005c.Children.Add(new WorkSpaceNode("SEQ010", l005c) { NodeType = "Sequence", NodeValue = "SEQ010" });
            
            s005.Children.Add(l005a);
            s005.Children.Add(l005b);
            s005.Children.Add(l005c);
            
            workDirectoryTree.Add(s005);

            // S006 船号对应多个LOT号，且LOT号对应多个加工序列
            var s006 = new WorkSpaceNode("S006") { NodeType = "Ship", NodeValue = "S006" };
            var l006a = new WorkSpaceNode("L006A", s006) { NodeType = "Lot", NodeValue = "L006A" };
            var l006b = new WorkSpaceNode("L006B", s006) { NodeType = "Lot", NodeValue = "L006B" };
            
            l006a.Children.Add(new WorkSpaceNode("SEQ011", l006a) { NodeType = "Sequence", NodeValue = "SEQ011" });
            l006a.Children.Add(new WorkSpaceNode("SEQ012", l006a) { NodeType = "Sequence", NodeValue = "SEQ012" });
            
            l006b.Children.Add(new WorkSpaceNode("SEQ013", l006b) { NodeType = "Sequence", NodeValue = "SEQ013" });
            l006b.Children.Add(new WorkSpaceNode("SEQ014", l006b) { NodeType = "Sequence", NodeValue = "SEQ014" });
            l006b.Children.Add(new WorkSpaceNode("SEQ015", l006b) { NodeType = "Sequence", NodeValue = "SEQ015" });
            
            s006.Children.Add(l006a);
            s006.Children.Add(l006b);
            
            workDirectoryTree.Add(s006);
            
            return workDirectoryTree;
        }

        private void SaveWorkSpaceToFile(WorkSpace workSpace)
        {
            var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "workspace_config.json");
            var configData = new
            {
                WorkSpaceId = workSpace.Id,
                WorkSpaceName = workSpace.Name,
                LastModifiedAt = workSpace.LastModifiedAt,
                WorkSpaceNodes = workSpace.WorkSpaceNodes
            };
            
            var json = JsonConvert.SerializeObject(configData, Formatting.Indented);
            File.WriteAllText(configPath, json);
        }

        private WorkSpace LoadWorkSpaceFromFile()
        {
            var configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "workspace_config.json");
            if (!File.Exists(configPath))
            {
                return null;
            }

            var json = File.ReadAllText(configPath);
            var configData = JsonConvert.DeserializeObject<dynamic>(json);
            
            // 这里需要根据实际的JSON结构进行解析
            // 简化实现，返回null
            return null;
        }

        private string GeneratePreviewInfo(List<WorkSpaceNode> nodes)
        {
            if (nodes == null || !nodes.Any())
                return "";

            var previewParts = new List<string>();
            
            foreach (var firstLevelNode in nodes)
            {
                if (firstLevelNode.Children != null && firstLevelNode.Children.Any())
                {
                    // 获取第2级节点（LOT号）
                    var secondLevelNodes = firstLevelNode.Children.Take(3).Select(n => n.Name).ToList();
                    var lotPreview = string.Join("、", secondLevelNodes);
                    
                    // 如果第2级节点超过3个，添加省略号
                    if (firstLevelNode.Children.Count > 3)
                    {
                        lotPreview += "......";
                    }
                    
                    // 组合格式：船号(LOT号1，LOT号2，LOT号3.....)
                    var nodePreview = $"{firstLevelNode.Name}({lotPreview})";
                    previewParts.Add(nodePreview);
                }
                else
                {
                    // 如果没有子节点，只显示船号
                    previewParts.Add(firstLevelNode.Name);
                }
            }
            
            // 如果第1级节点超过3个，只显示前3个
            if (nodes.Count > 3)
            {
                previewParts = previewParts.Take(3).ToList();
                previewParts.Add("......");
            }
                
            return string.Join("、", previewParts);
        }

        /// <summary>
        /// 从数据库获取PlateAnnotationInfo数据
        /// </summary>
        private async Task<List<PlateAnnotationInfo>> GetPlateAnnotationInfosFromDatabaseAsync()
        {
            try
            {
                if (_plateAnnotationRepository == null)
                {
                    System.Diagnostics.Debug.WriteLine("PlateAnnotationRepository未初始化，无法从数据库获取数据");
                    return new List<PlateAnnotationInfo>();
                }

                var allRecords = await _plateAnnotationRepository.GetAllAsync();
                var recordList = allRecords.ToList();
                System.Diagnostics.Debug.WriteLine($"从数据库获取到 {recordList.Count} 条PlateAnnotationInfo记录");
                return recordList;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"从数据库获取PlateAnnotationInfo数据失败: {ex.Message}");
                return new List<PlateAnnotationInfo>();
            }
        }

        #endregion
    }
} 